/**
 * 三维模型渲染
 * @param {*} tileset 模型
 * @param {*} checked 是否渲染
 * @param {*} Cesium 
 * @param {*} option 
 */
export const shaderModel = (tileset, checked, Cesium, option = {}) => {
  var curTs = tileset;
  if (!Cesium.defined(curTs.customShader) && checked) {
    let customShader = new Cesium.CustomShader({
      // configure where in the fragment shader's materials/lighting pipeline the
      // custom shader goes. More on this below.
      mode: Cesium.CustomShaderMode.MODIFY_MATERIAL,
      // either PBR (physically-based rendering) or UNLIT depending on the desired
      // results.
      lightingModel: Cesium.LightingModel.PBR,
      // Force the shader to render as transparent, even if the primitive had
      // an opaque material
      translucencyMode: Cesium.CustomShaderTranslucencyMode.OPAQUE,
      // Custom vertex shader. This is a function from model space -> model space.
      // VertexInput is documented below

      uniforms: {
        u_heiInfo: {
          type: Cesium.UniformType.VEC2,
          value: new Cesium.Cartesian3(-78, 78), //current model's minHei and maxHei in model space
        },
      },

      //片元着色器
      fragmentShaderText: `
       precision highp float;
       void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
       float curZ = fsInput.attributes.positionMC.z;
        
       //five colors construct four strips
       vec3 cols[5];
       cols[4]=vec3(1.0,0.3,0.3);
       cols[3]=vec3(1.0,0.75,0.0);
       cols[2]=vec3(0.57,0.81,0.3);
       cols[1]=vec3(0.0,0.8,0.6);
       cols[0]=vec3(0.42,0.6,0.75);

        float totalHei=u_heiInfo.y-u_heiInfo.x;
        float deltaHei=totalHei/4.0;
        float minHei=0.0;
        float maxHei=0.0;
        int colorIndex=0;
        for(int i=0;i<4;i++){
          minHei=u_heiInfo.x+float(i)*deltaHei;
          maxHei=minHei+deltaHei;
          colorIndex=i;
          if(curZ>=minHei && curZ<=maxHei)
            break;
        }
        
        float delta=(curZ-minHei)/deltaHei;
       // material.diffuse = cols[colorIndex+1];
        material.diffuse = mix(cols[colorIndex],cols[colorIndex+1],delta);

      }`,
    });

    curTs.customShader = customShader;
    const box = curTs.root._header.boundingVolume.box;
    customShader.setUniform(
      "u_heiInfo",
      new Cesium.Cartesian2(box[2] - box[11], box[2] + box[11])
    );
  } else {
    curTs.customShader = undefined;
  }
}
